package pri.zxx.webdemo.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pri.zxx.webdemo.entity.vo.ResultData;

import jakarta.servlet.http.HttpServletRequest;
import java.util.stream.Stream;

/**
 * @author TJ2020-6
 * @desc
 * @createTime 2020-07-09-13:40
 */
@Aspect
@Component
@Slf4j
public class IpAspect {

    @Autowired
    private WxPayBaseConfig wxPayBaseConfig;

    @Pointcut(value = "execution(public * pri.zxx.webdemo.controllers..*(..))")
    public void execute() {
    }

    @Around("execute()")
    public Object doPre(ProceedingJoinPoint jp) throws Throwable {

        LimitIp annotation = (LimitIp) AopUtil.getAnnotation(jp, LimitIp.class);

        if (annotation != null) {
            //判断是否在允许通过的ip中
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
            HttpServletRequest request = sra.getRequest();

            request.setAttribute("useInfo",new Object());

            String ipAddr = HttpUtils.getIpAddr(request);
            boolean contains = false;
            String[] banned = annotation.banned();
            if (banned != null && banned.length > 0) {
                if (Stream.of(banned).anyMatch(s -> s.equals(ipAddr))) {
                    log.warn("---->>请求ip:{} 【拦截】 {}", ipAddr, AopUtil.requestInfo(request, jp));
                    return ResultData.fail("错误#1111");
                }
            }
            String[] allow = annotation.allow();
            if (allow.length > 0) {
                contains = Stream.of(allow).anyMatch(s -> s.equals(ipAddr));
            }
            if (!contains) {
                contains = wxPayBaseConfig.getAllowedIps().contains(ipAddr);
            }
            if (!contains) {
                log.warn("---->>请求ip:{} 【拦截】{}", ipAddr, AopUtil.requestInfo(request, jp));
                return ResultData.fail("错误#1111");
            }
            log.warn("---->>请求ip:{} 【通过】", ipAddr);
        }
        return jp.proceed();
    }
}
